package com.wisewin.circle.api.controller;
import com.wisewin.circle.api.controller.base.BaseController;
import com.wisewin.circle.config.dto.ResultDTO;
import com.wisewin.circle.config.dto.ResultDTOBuilder;
import com.wisewin.circle.entity.LoginUser;
import com.wisewin.circle.entity.bo.QueryParamBO;
import com.wisewin.circle.entity.db.OrgUserDO;
import com.wisewin.circle.entity.db.UserDO;
import com.wisewin.circle.entity.db.UserVisitDO;
import com.wisewin.circle.service.*;
import com.wisewin.circle.util.DateUtil;
import com.wisewin.circle.util.MD5Util;
import com.wisewin.circle.util.NicknameGenerator;
import com.wisewin.circle.util.TencentcloudUtil;
import com.wisewin.circle.util.env.Env;
import com.wisewin.circle.util.tencentyun.TencentCloudImUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
	final static Logger log = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService userService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private WechatAuthService wechatAuthService;

	@PostMapping("/queryUserById")
	public ResultDTO queryUserById (@RequestBody UserDO userDO) {
		return userService.queryUserById(userDO.getId());
	}

	// 登录接口
	@PostMapping("/login")
	public ResultDTO login (@RequestBody UserDO userDO) {
		UserDO user = userService.queryUserByPhonePasscode(userDO);
		if(user == null){
			return ResultDTOBuilder.failure("1", "用户不存在", null) ;
		}
		// 封装登录对象
		LoginUser loginUser = new LoginUser();
		loginUser.setId(user.getId());
		loginUser.setUserName(user.getUserName());
		String sessionID = super.setLoginUser(loginUser);
		// 生成SessionId
		loginUser.setSessionId(sessionID);
		return ResultDTOBuilder.success(loginUser);
	}

	// 查询用户基本信息
	@PostMapping("/queryUserInfo")
	public ResultDTO queryUserInfo(HttpServletRequest request, @RequestBody QueryParamBO queryParamBO){
		String token = request.getHeader("token");
		LoginUser loginUser = null;
		if(!StringUtils.isEmpty(token)){
			// 获取登录用户
			loginUser = super.getLoginUser(token);
			if (loginUser == null ) { // 判断是否登录
				return ResultDTOBuilder.failure("0000001", "登录已过期", null);
			}
		}
		// 处理id
		Integer loginUserId = loginUser == null ? null : loginUser.getId();
		Integer userId = queryParamBO.getUserId() == null ? loginUserId : queryParamBO.getUserId();
		Integer visitUserId = queryParamBO.getUserId();
		return userService.queryUserInfo(userId, loginUserId, visitUserId);
	}

	// 上传用户头像
	@PostMapping("/uploadUserHeadUrl")
	public ResultDTO uploadUserHeadUrl (HttpServletRequest request, MultipartFile[] lstFile) {
		String token = request.getHeader("token");
		if(StringUtils.isEmpty(token)){
			return ResultDTOBuilder.failure("0000005", "必传参数为空", null);
		}
		Integer userId = null;
		// 获取登录用户
		if(token.startsWith("user_")) {
			LoginUser loginUser = super.getLoginUser(token);
			if (loginUser == null) { // 判断是否登录
				return ResultDTOBuilder.failure("0000001", "登录已过期", null);
			}
			userId = loginUser.getId();
		}else if(token.startsWith("orguser_")){
			// 获取登录用户
			OrgUserDO orgUserDO = super.getOrgLoginUser(token);
			if (orgUserDO == null ) { // 判断是否登录
				return ResultDTOBuilder.failure("0000001", "登录已过期", null);
			}
			userId = orgUserDO.getId();
		}
		return activityService.uploadFile(lstFile, userId, "userHeadUrl");
	}

	// 修改用户基本信息
	@PostMapping("/updateUserInfo")
	public ResultDTO updateUserInfo (HttpServletRequest request, @RequestBody UserDO userDO) {
		String token = request.getHeader("token");
		if(StringUtils.isEmpty(token)){
			return ResultDTOBuilder.failure("0000005", "必传参数为空", null);
		}
		// 获取登录用户
		if(token.startsWith("user_")) {
			LoginUser loginUser = super.getLoginUser(token);
			if (loginUser == null) { // 判断是否登录
				return ResultDTOBuilder.failure("0000001", "登录已过期", null);
			}
			userDO.setId(loginUser.getId());
		}else if(token.startsWith("orguser_")){
			// 获取登录用户
			OrgUserDO orgUserDO = super.getOrgLoginUser(token);
			if (orgUserDO == null ) { // 判断是否登录
				return ResultDTOBuilder.failure("0000001", "登录已过期", null);
			}
		}
		return userService.updateUserInfo(userDO);
	}

	// 查询用户列表
	@PostMapping("/queryUserList")
	public ResultDTO queryUserList (HttpServletRequest request, @RequestBody QueryParamBO queryParamBO) {
		String token = request.getHeader("token");
		if(StringUtils.isEmpty(token)){
			return ResultDTOBuilder.failure("0000005", "必传参数为空", null);
		}
		// 获取登录用户
		OrgUserDO orgUserDO = super.getOrgLoginUser(token);
		if (orgUserDO == null ) { // 判断是否登录
			return ResultDTOBuilder.failure("0000001", "登录已过期", null);
		}
		return userService.queryUserList(queryParamBO, getPageQuery(queryParamBO.getPageNo(), queryParamBO.getPageSize()));
	}

	// 后台创建用户
	@PostMapping("/addUser")
	public ResultDTO addUser (HttpServletRequest request, @RequestBody UserDO userDO) {
		String token = request.getHeader("token");
		if(StringUtils.isEmpty(token)){
			return ResultDTOBuilder.failure("0000005", "必传参数为空", null);
		}
		// 获取登录用户
		OrgUserDO orgUserDO = super.getOrgLoginUser(token);
		if (orgUserDO == null ) { // 判断是否登录
			return ResultDTOBuilder.failure("0000001", "登录已过期", null);
		}
		// 创建人id
		userDO.setOrgUserId(orgUserDO.getId());
		return userService.addUser(userDO);
	}

	// 删除用户
	@PostMapping("/deleteUser")
	public ResultDTO deleteUser (HttpServletRequest request, @RequestBody UserDO userDO) {
		String token = request.getHeader("token");
		if(StringUtils.isEmpty(token)){
			return ResultDTOBuilder.failure("0000005", "必传参数为空", null);
		}
		// 获取登录用户
		OrgUserDO orgUserDO = super.getOrgLoginUser(token);
		if (orgUserDO == null ) { // 判断是否登录
			return ResultDTOBuilder.failure("0000001", "登录已过期", null);
		}
		return userService.deleteUser(userDO.getId());
	}

	// 启用、禁用用户
	@PostMapping("/updateUserStatus")
	public ResultDTO updateUserStatus (HttpServletRequest request, @RequestBody QueryParamBO queryParamBO) {
		String token = request.getHeader("token");
		if(StringUtils.isEmpty(token)){
			return ResultDTOBuilder.failure("0000005", "必传参数为空", null);
		}
		// 获取登录用户
		OrgUserDO orgUserDO = super.getOrgLoginUser(token);
		if (orgUserDO == null ) { // 判断是否登录
			return ResultDTOBuilder.failure("0000001", "登录已过期", null);
		}
		return userService.updateUserStatus(queryParamBO);
	}

	// 添加用户访问记录
	@PostMapping("/addUserVisit")
	public ResultDTO addUserVisit (HttpServletRequest request, @RequestBody UserVisitDO userVisitDO) {
		String token = request.getHeader("token");
		if(StringUtils.isEmpty(token)){
			return ResultDTOBuilder.failure("0000005", "必传参数为空", null);
		}
		// 获取登录用户
		LoginUser loginUser = super.getLoginUser(token);
		if (loginUser == null ) { // 判断是否登录
			return ResultDTOBuilder.failure("0000001", "登录已过期", null);
		}
		userVisitDO.setUserId(loginUser.getId());
		return userService.addUserVisit(userVisitDO);
	}

	// 查询用户访客列表
	@PostMapping("/queryUserVisitList")
	public ResultDTO queryUserVisitList (HttpServletRequest request, @RequestBody QueryParamBO queryParamBO) {
		String token = request.getHeader("token");
		if(StringUtils.isEmpty(token)){
			return ResultDTOBuilder.failure("0000005", "必传参数为空", null);
		}
		// 获取登录用户
		LoginUser loginUser = super.getLoginUser(token);
		if (loginUser == null ) { // 判断是否登录
			return ResultDTOBuilder.failure("0000001", "登录已过期", null);
		}
		queryParamBO.setUserId(loginUser.getId());
		return userService.queryUserVisitList(queryParamBO, getPageQuery(queryParamBO.getPageNo(), queryParamBO.getPageSize()));
	}

	// 修改个人主页图片接口
	@PostMapping("/updateUserHomeUrl")
	public ResultDTO updateUserHomeUrl (HttpServletRequest request, @RequestBody UserDO userDO) {
		String token = request.getHeader("token");
		if(StringUtils.isEmpty(token)){
			return ResultDTOBuilder.failure("0000005", "必传参数为空", null);
		}
		// 获取登录用户
		LoginUser loginUser = super.getLoginUser(token);
		if (loginUser == null ) { // 判断是否登录
			return ResultDTOBuilder.failure("0000001", "登录已过期", null);
		}
		userDO.setId(loginUser.getId());
		return userService.updateUserHomeUrl(userDO);
	}

	// 获取微信登录手机号码
	@PostMapping("/getPhoneNumber")
	public ResultDTO getPhoneNumber (@RequestBody QueryParamBO queryParamBO) {
		String appId = Env.getProperty("wechatAppId");
		return wechatAuthService.getPhoneNumber(queryParamBO.getCode(), appId);
	}

	/**
	 * 登录、注册
	 */
	@PostMapping("/loginUser")
	public ResultDTO loginUser (@RequestBody UserDO user) {
		TencentCloudImUtil tencentCloudImUtil = new TencentCloudImUtil();
		// 验证必传参数
		if(StringUtils.isEmpty(user.getPhone())){
			return ResultDTOBuilder.failure("1", "参数有误", null);
		}
		// 判断手机号码格式是否有误
		if(!DateUtil.isMobile(user.getPhone())){
			return ResultDTOBuilder.failure("1", "手机号码格式有误", null);
		}
		// 通过身份证查找用户
		LoginUser userDO = userService.queryUserInfoByPhone(user.getPhone());
		// 说明已经注册过
		if (userDO != null) {
			if(userDO.getIsDel() == 1){
				return ResultDTOBuilder.failure("1", "当前用户已禁用，请联系管理员！", null);
			}
			String sessionID = super.setLoginUser(userDO);
			// 生成SessionId
			userDO.setSessionId(sessionID);
			userDO.setImAppId(Env.getProperty("imAppId"));
			userDO.setImAppSecretkey(Env.getProperty("imAppSecretkey"));
			// 腾讯im导入单个帐号
			tencentCloudImUtil.accountImport(userDO.getId().toString(), userDO.getUserName(), userDO.getHeadUrl());
			String userSig = tencentCloudImUtil.getTxCloudUserSig(userDO.getId().toString());
			userDO.setUserSig(userSig);
			return ResultDTOBuilder.success(userDO);
		} else {
			// 走注册流程
			UserDO insert = new UserDO();
			insert.setPhone(user.getPhone());
			insert.setPasscode(MD5Util.digest(user.getPhone()));
			insert.setUserName(NicknameGenerator.generateRandomNickname(12));
			insert.setHeadUrl(Env.getProperty("headUrlDefault"));
			insert.setIntroduce("");
			insert.setCreateTime(new Date());
			userService.insertPhone(insert);
			LoginUser loginUser = new LoginUser();
			loginUser.setId(insert.getId());
			loginUser.setPhone(insert.getPhone());
			loginUser.setUserName(insert.getUserName());
			loginUser.setHeadUrl(insert.getHeadUrl());
			String sessionID = super.setLoginUser(loginUser);
			// 生成SessionId
			loginUser.setSessionId(sessionID);
			loginUser.setImAppId(Env.getProperty("imAppId"));
			loginUser.setImAppSecretkey(Env.getProperty("imAppSecretkey"));
			// 腾讯im导入单个帐号
			tencentCloudImUtil.accountImport(loginUser.getId().toString(), loginUser.getUserName(), loginUser.getHeadUrl());
			String userSig = tencentCloudImUtil.getTxCloudUserSig(loginUser.getId().toString());
			loginUser.setUserSig(userSig);
			return ResultDTOBuilder.success(loginUser);
		}
	}
}
